﻿#pragma once

#include <iostream>
using namespace std;

template<class K>
struct TreeNode
{
public:
	TreeNode* _left;
	TreeNode* _right;
	K _key;
	TreeNode(K key)
		:_key(key)
		,_left(nullptr)
		,_right(nullptr)
	{ }
};

template<class K>
class BSTree
{
public:
	BSTree()
		:_root(nullptr)
	{ }
	// 若存在则返回false，不存在则插入并返回true
	bool Insert(K key)
	{
		if (_root == nullptr)
		{
			_root = new TreeNode<K>(key);
			return true;
		}
		TreeNode<K>* cur = _root;
		TreeNode<K>* parent = nullptr;
		while (cur)
		{
			parent = cur;
			if (key < cur->_key)
			{
				cur = cur->_left;
			}
			else if (key > cur->_key)
			{
				cur = cur->_right;
			}
			else
			{
				return false;
			}
		}
		if (key < parent->_key)
		{
			parent->_left = new TreeNode<K>(key);
		}
		else
		{
			parent->_right = new TreeNode<K>(key);
		}
		return true;
	}
	// 若不存在则返回false，存在则删除并返回true
	bool Erase(int key)
	{
		TreeNode<K>* cur = _root;
		TreeNode<K>* parent = nullptr;
		while (cur)
		{
			if (key < cur->_key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else if (key > cur->_key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_right;
					}
					else
					{
						if (cur == parent->_left)
						{
							parent->_left = cur->_right;
						}
						else
						{
							parent->_right = cur->_right;
						}
					}
					delete cur;
				}
				else if (cur->_right == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_left;
					}
					else
					{
						if (cur == parent->_left)
						{
							parent->_left = cur->_left;
						}
						else
						{
							parent->_right = cur->_left;
						}
					}
					delete cur;
				}
				else
				{
					TreeNode<K>* rparent = cur;
					TreeNode<K>* rcur = cur->_right;
					while (rcur->_left)
					{
						rparent = rcur;
						rcur = rcur->_left;
					}
					std::swap(rcur->_key, cur->_key);
					if (rcur == rparent->_left)
					{
						rparent->_left = rcur->_right;
					}
					else
					{
						rparent->_right = rcur->_right;
					}
					delete rcur;
				}
				return true;
			}
		}
		return false;
	}
	bool Find(K key)
	{
		TreeNode<K>* cur = _root;
		while (cur)
		{
			if (key < cur->_key)
			{
				cur = cur->_left;
			}
			else if (key > cur->_key)
			{
				cur = cur->_right;
			}
			else
			{
				return true;
			}
		}
		return false;
	}
	void InOrder()
	{
		_InOrder(_root);
	}
private:
	void _InOrder(TreeNode<K>* root)
	{
		if (root == nullptr) {
			return;
		}
		_InOrder(root->_left);
		cout << root->_key << " ";
		_InOrder(root->_right);
	}
private:
	TreeNode<K>* _root;
};